package leetcode;

public class AddStrings {

	public static void main(String[] args) {
		AddStrings object = new AddStrings();
		String num1 = "945";
		String num2 = "154";
		System.out.println(object.addStrings(num1, num2));
	}

	public String addStrings(String num1, String num2) {
		if (num1 == null || num2 == null) {
			return "";
		}
		int length1 = num1.length();
		int length2 = num2.length();
		if (length1 == 0 || length2 == 0) {
			return length1 == 0 ? num2 : num1;
		}
		// 数组的低位存储低位
		char[] chas1 = new StringBuilder(num1).reverse().toString()
				.toCharArray();
		char[] chas2 = new StringBuilder(num2).reverse().toString()
				.toCharArray();
		int maxLength = Math.max(length1, length2);
		char[] chas = new char[maxLength];
		int carry = 0;
		for (int i = 0; i < maxLength; i++) {
			int res = (i >= length1 ? 0 : chas1[i] - '0')
					+ (i >= length2 ? 0 : chas2[i] - '0') + carry;
			chas[i] = (char) (res % 10 + '0');
			carry = res / 10;
		}
		String res = String.valueOf(chas);
		StringBuilder sb = new StringBuilder(res).reverse();
		System.out.println("res: " + res);
		if (carry != 0) {
			sb.insert(0, carry);
		}
		return sb.toString();
	}

	// other's code
	public String addStrings2(String num1, String num2) {
		// 这样可以保证num1是长字符串
		if (num1.length() < num2.length())
			return addStrings2(num2, num1);
		
		int carry = 0, i = num1.length() - 1, j = num2.length() - 1;
		char[] nums1 = num1.toCharArray();
		char[] nums2 = num2.toCharArray();
		for (; i >= 0 && (carry == 1 || j >= 0); i--, j--, carry /= 10)
			nums1[i] = (char) ((carry += nums1[i] - '0'
					+ (j >= 0 ? nums2[j] - '0' : 0)) % 10 + '0');
		return (carry == 1 ? "1" : "") + num1;
	}
}
